﻿using AutoMapper;
using MD5Hash;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Users;

namespace RBAC.Api.Writh.CommandHandler.Users
{
    public class AddUserCommandHandler : IRequestHandler<AddUserCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<User> users;
        private readonly IMapper mapper;
        private readonly IBaseRepositry<UserRole> userrole;
        private readonly ILogger<AddUserCommandHandler> logger1;

        public AddUserCommandHandler(IBaseRepositry<User> baseRepositry, 
                        IMapper mapper,
                        IBaseRepositry<UserRole> baseRepositry1,
                        ILogger<AddUserCommandHandler> logger1)
        {
            this.users = baseRepositry;
            this.mapper = mapper;
            this.userrole = baseRepositry1;
            this.logger1 = logger1;
        }
        public async Task<APIResult<object>> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result=new APIResult<object>();
            result.Code = ResultCode.Success;
            result.Message = "添加用户角色成功";

            var strategy = users.Context.Database.CreateExecutionStrategy();
            await strategy.ExecuteAsync(async () =>
            {
                using (var tran = await users.Context.Database.BeginTransactionAsync())
                {
                    try
                    { 
                        //添加用户
                        var user = mapper.Map<User>(request);
                        user.Password=request.Password.GetMD5();
                        user.State = request.State; // 确保状态字段被正确设置
                        logger1.LogInformation($"添加用户:{user}");
                        await users.Add(user);

                        //添加用户角色
                        foreach (var item in request.RoleId)
                        {
                            UserRole userRole = new UserRole
                            {
                                UserId = user.Id,
                                RoleId = item,
                                CreateTime = DateTime.Now,
                                State = request.State // 设置用户角色关联的状态与用户状态一致
                            };
                            logger1.LogInformation($"添加用户角色:{userRole}");
                            await userrole.Add(userRole);
                        };
                        await tran.CommitAsync();
                    }
                    catch (Exception ex)
                    {
                        await tran.RollbackAsync();
                        result.Code = ResultCode.Fail;
                        result.Message = "添加用户角色失败";
                    }
                }
            });
            return await Task.FromResult(result);
        }
    }
}
